<template>
  <view class="container">
    <!-- 地图组件 -->
    <map id="locationMap" style="width: 100%; height: 100vh;" :latitude="latitude" :longitude="longitude"
         :markers="markers" :polygons="polygons" :show-location="true"></map>
    <!-- 手动点名按钮 -->
    <view class="button-container">
      <button class="rollcall-btn" @click="getBtn">{{rollcallText}}</button>
    </view>
    <!-- 统计信息展示区域 -->
    <view class="statistics-container" v-if="showStatistics">
      <view class="count-container">
        <view class="inside-count">
          <text class="statistic-num green-text">{{insideCount}} 头</text>
          <text class="statistic-label green-label">栏内</text>
        </view>
        <view class="outside-count">
          <text class="statistic-num orange-text">{{outsideCount}} 头</text>
          <text class="statistic-label orange-label">栏外</text>
        </view>
      </view>
      <view class="area-perimeter-container">
        <view class="area-container">
          <image class="area-icon" src="/static/map/area.jpg"></image>
          <text class="area-text">面积: {{area}}㎡</text>
        </view>
        <view class="perimeter-container">
          <image class="perimeter-icon" src="/static/map/p.png"></image>
          <text class="perimeter-text">周长: {{perimeter}}m</text>
        </view>
      </view>
    </view>
    <!-- 错误提示区域 -->
    <view class="error-tip" v-if="errorMsg">
      <text class="error-text">{{errorMsg}}</text>
    </view>
  </view>
</template>

<script>
// 修正导入语法位置和方式
import { getMapFence } from '@/utils/api/map.js'

export default {
  data() {
    return {
      latitude: 0,
      longitude: 0,
      markers: [],
      polygons: [
        {
          points: [],
          strokeColor: '#07c160',
          fillColor: 'rgba(7, 193, 96, 0.2)',
          strokeWidth: 2,
          strokeOpacity: 1,
          fillOpacity: 0.2,
          zIndex: 100
        }
      ],
      apiFenceInfo: [],
      apiLocationInfo: [],
      apiNumInfo: {},
      rollcallText: '开始点名',
      showStatistics: false,
      insideCount: 0,
      outsideCount: 0,
      area: 0,
      perimeter: 0,
      errorMsg: ''
    };
  },
  onLoad() {
    this.fetchMapData();
  },
  methods: {
    isPointInPolygon(point, polygon) {
      if (!polygon || polygon.length === 0) return false;
      let inside = false;
      for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
        const xi = polygon[i].longitude;
        const yi = polygon[i].latitude;
        const xj = polygon[j].longitude;
        const yj = polygon[j].latitude;
        const intersect = ((yi > point.latitude) !== (yj > point.latitude)) &&
          (point.longitude < (xj - xi) * (point.latitude - yi) / (yj - yi) + xi);
        if (intersect) inside = !inside;
      }
      return inside;
    },
    async fetchMapData() {
      this.errorMsg = '';
      try {
        // 使用封装的axios请求
        const res = await getMapFence();
        
        if (res.code === 200) {
          this.apiFenceInfo = res.data.fenceInfo || [];
          this.apiLocationInfo = res.data.locationInfo || [];
          this.apiNumInfo = res.data.NumInfo && res.data.NumInfo[0] || {};

          // 解析F_Map JSON字符串
          const firstFence = this.apiFenceInfo[0];
          if (!firstFence || !firstFence.F_Map) {
            this.errorMsg = '围栏数据缺失F_Map字段';
            return;
          }

          try {
            const fMap = JSON.parse(firstFence.F_Map); // 解析JSON字符串
            const fencePaths = fMap.paths || [];
            
            // 验证路径数据格式（确保包含lat和lng，且为数字类型）
            if (!Array.isArray(fencePaths) || fencePaths.some(path => 
              isNaN(path.lat) || isNaN(path.lng) || 
              typeof path.lat !== 'number' || typeof path.lng !== 'number'
            )) {
              this.errorMsg = '围栏路径数据格式错误';
              return;
            }

            this.polygons[0].points = fencePaths.map(path => ({
              latitude: path.lat,
              longitude: path.lng
            }));
          } catch (parseError) {
            this.errorMsg = '围栏数据解析失败，请检查F_Map格式';
            console.error('JSON解析错误:', parseError);
            return;
          }

          // 处理牛牛位置数据（转换字符串为数字）
          if (this.apiLocationInfo.length > 0) {
            this.markers = this.apiLocationInfo.map((loc, index) => ({
              id: index + 1,
              latitude: Number(loc.lat), // 字符串转数字
              longitude: Number(loc.lng), // 字符串转数字
              iconPath: '/static/map/seat.png',
              width: 20,
              height: 20
            }));
          } else {
            this.errorMsg = '没有获取到牛牛位置信息';
            return;
          }

          // 设置地图中心为围栏第一个点
          if (this.polygons[0].points.length > 0) {
            const firstPoint = this.polygons[0].points[0];
            this.latitude = firstPoint.latitude;
            this.longitude = firstPoint.longitude;
          }

          this.area = this.apiNumInfo.F_Area || 0;
          this.perimeter = this.apiNumInfo.F_Zc || 0;
          this.updateCowCounts();
        } else {
          this.errorMsg = `接口请求失败：${res.msg || '未知错误'}`;
          console.error('接口响应:', res);
        }
      } catch (error) {
        this.errorMsg = `网络请求失败：${error.message}`;
        console.error('请求异常:', error);
      }
    },

    // 更新围栏内外数量
    updateCowCounts() {
      const polygonPoints = this.polygons[0].points;
      if (polygonPoints.length === 0) return;

      let insideCount = 0;
      this.markers.forEach(marker => {
        if (this.isPointInPolygon(marker, polygonPoints)) {
          insideCount++;
        }
      });

      this.insideCount = insideCount;
      this.outsideCount = this.markers.length - insideCount;
    },

    // 手动点名方法 - 修改为驼峰命名
    getBtn() {
      if (this.rollcallText === '开始点名') {
        this.rollcallText = '点名中...';
        this.errorMsg = '';

        setTimeout(() => {
          if (this.polygons[0].points.length === 0) {
            this.errorMsg = '围栏数据未加载完成，请稍后再试';
            this.rollcallText = '开始点名';
            return;
          }

          this.updateCowCounts();
          this.showStatistics = true;
          this.rollcallText = '点名完成';

          setTimeout(() => {
            this.rollcallText = '开始点名';
            this.showStatistics = false;
          }, 5000);
        }, 1500);
      }
    }
  }
};
</script>

<style>
/* 样式部分保持不变 */
.container {
  position: relative;
  width: 100%;
  height: 100%;
}
.button-container {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
}
.rollcall-btn {
  width: 100px;
  height: 100px;
  background-color: #07c160;
  color: white;
  font-size: 16px;
  border: none;
  border-radius: 50%;
    display: flex; /* 新增flex布局 */
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    padding: 0; /* 清除默认内边距 */
}
.statistics-container {
  position: fixed;
  bottom: 80px;
  left: 10px;
  right: 10px;
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 100;
  margin-bottom: -70px;
}
.count-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}
.inside-count,
.outside-count {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.area-perimeter-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.area-container,
.perimeter-container {
  display: flex;
  align-items: center;
}
.area-icon,
.perimeter-icon {
  width: 20px;
  height: 20px;
  margin-right: 10px;
  opacity: 0.8;
}
.area-text,
.perimeter-text {
  font-size: 18px;
  color: #333;
}
.statistic-num {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 5px;
}
.green-text {
  color: #00b359;
}
.orange-text {
  color: #ff7a00;
}
.statistic-label {
  padding: 6px 14px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  background-color: rgba(0, 0, 0, 0.08);
}
.green-label {
  color: #00b359;
}
.orange-label {
  color: #ff7a00;
}
/* 错误提示样式 */
.error-tip {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #ff4545;
  color: white;
  padding: 8px 15px;
  border-radius: 4px;
  z-index: 300;
}
.error-text {
  font-size: 14px;
}
</style>